﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Collections.Generic;

namespace UI
{
    public partial class AddPrinter : UserControl
    {

        ClientContext context;
        List customerList, listForUpload, printerModels, printerDrivers;
        ListItemCollection models,drivers;
        private string[] datas;
        string[] fluff;
        Point pt;
        public AddPrinter(string[] f, Point p)
        {
            InitializeComponent();
            context = ClientContext.Current;
            Guid mods = new Guid("E13831E1-AD8C-42DA-8FE2-F62BB793C6D5");//list of makes and models - changed
            printerModels = context.Web.Lists.GetById(mods);
            context.Load(printerModels);
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"<View><Query></Query><RowLimit>1000</RowLimit></View>";
            models = printerModels.GetItems(camlQuery);
            context.Load(models);
            
            fluff = f;
            pt = p;
            datas = new string[2] { context.Url.ToString() + @"/PrinterScripts/" + fluff[0] + textBox4.Text + "-" + comboBox1.SelectionBoxItem.ToString() + comboBox2.SelectedItem.ToString() + ".vbs", textBox1.Text };
            context.ExecuteQueryAsync(closeafter, null);
        }
        private void OnUploadRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
        {
            Dispatcher.BeginInvoke(upload);
        }
        private void upload()
        {
            
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string towrite;
                string a = fluff[0] + textBox4.Text + "-" + comboBox1.SelectionBoxItem.ToString() + comboBox2.SelectedItem.ToString() + ".vbs";
                var isoStream = store.OpenFile(a, FileMode.OpenOrCreate);
                string name = @"\\c2031sfile2\2031CAT-" + fluff[0] + textBox4.Text + "-" + comboBox1.SelectionBoxItem.ToString() + comboBox2.SelectedItem.ToString() + "\""; // fluff[0] is room 
                towrite = "Set objNetwork = CreateObject(\"WScript.Network\")\n objNetwork.AddWindowsPrinterConnection \"" + name + "\n objNetwork.SetDefaultPrinter \"" + name;
                isoStream.Write(Encoding.UTF8.GetBytes(towrite), 0, Encoding.UTF8.GetBytes(towrite).Length);
                isoStream.Close();
                var fci = new SP.FileCreationInformation();
                isoStream = new IsolatedStorageFileStream(a, FileMode.Open, store);
                byte[] fileBytes = new byte[isoStream.Length];
                isoStream.Read(fileBytes, 0, (int)isoStream.Length);
                fci.Content = fileBytes;
                fci.Url = a;
                Guid b = new Guid("C81B8B0A-2185-4012-A893-4624F8FBADA2");//library where the scripts get uploaded - changed
                listForUpload = context.Web.Lists.GetById(b);
                Microsoft.SharePoint.Client.File clFile = listForUpload.RootFolder.Files.Add(fci);
                context.Load(clFile);
                store.Dispose();
                datas = new string[2] { context.Url.ToString() + @"/PrinterScripts/" + fluff[0] + textBox4.Text + "-" + comboBox1.SelectionBoxItem.ToString() + comboBox2.SelectedItem.ToString() + ".vbs", textBox1.Text };
            }
            context.ExecuteQueryAsync(thiss, null);
        }
        private void closeafter(object sender, ClientRequestSucceededEventArgs args)
        {
            Dispatcher.BeginInvoke(populateModels);
        }
        private void thiss(object sender, ClientRequestSucceededEventArgs args)
        { }
        private void populateModels()
        {
            List<string> makes = new List<string>();
            foreach (ListItem item in models)
            {
                if (!makes.Contains(item["Make"].ToString()))
                {
                    makes.Add(item["Make"].ToString());
                }

            }
            comboBox1.ItemsSource = makes;
            
        }
        public string[] Datas
        {
            get; set;
        }
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            datas = new string[2] { context.Url.ToString() + @"/PrinterScripts/" + fluff[0] + textBox4.Text + "-" + comboBox1.SelectionBoxItem.ToString() + comboBox2.SelectedItem.ToString() + ".vbs", textBox1.Text };
            Guid PrinterGuid = new Guid("5B6AB860-2EC6-471E-919D-E209E11B3E73");//list of the printers
            customerList = context.Web.Lists.GetById(PrinterGuid);
            ListItem items;
            ListItemCreationInformation itemcreationinfo = new ListItemCreationInformation();
            items = customerList.AddItem(itemcreationinfo);
            items["Script_x0020_URL"] = context.Url.ToString() + @"/PrinterScripts/" + fluff[0] + textBox4.Text + "-" + comboBox1.SelectionBoxItem.ToString() + comboBox2.SelectedItem.ToString() + ".vbs";
            items["Title"] = textBox1.Text;
            items["make"] = comboBox1.SelectionBoxItem.ToString();
            items["model"] = comboBox2.SelectedItem.ToString();
            items["x"] = pt.X - 249;
            items["y"] = pt.Y - 40;
            items["building"] = fluff[0];
            items["room"] = textBox4.Text;
            items.Update();
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"<View><Query></Query><RowLimit>1000</RowLimit></View>";
            Guid driverList = new Guid("9576EA9A-004F-4A1A-B377-EFCC506F2330");//list of driver paths
            printerDrivers = context.Web.Lists.GetById(driverList);
            context.Load(printerDrivers);
            drivers = printerDrivers.GetItems(camlQuery);
            context.Load(drivers);
            context.ExecuteQueryAsync(OnUploadRequestSucceeded, null);
        }

        public string[] datareturn()
        {
            return datas;
        }
        

        private void comboBox1_DropDownClosed(object sender, EventArgs e)
        {
            List<string> model = new List<string>();
            foreach (ListItem item in models)
            {
                if (item["Make"].ToString().Equals(comboBox1.SelectedValue.ToString()))
                {
                    model.Add(item["Model"].ToString());
                }

            }
            comboBox2.ItemsSource = model;
            
            
        }

    }
}
